# -*- coding: UTF-8 -*-
import MySQLdb
import hashlib
from config import Config
class DbUtils:
    def __init__(self):
       config_db_proxy = Config('spider.conf')
       config_db_proxy.readDb()
       self.db = MySQLdb.connect(host=config_db_proxy.host, user=config_db_proxy.user, passwd=config_db_proxy.passwd, db=config_db_proxy.db_data,charset="utf8")

    def insert(self,url,content,forward,praise,comment,classify,medium,media,company,province,createtime,dateline,title,city):

       content = MySQLdb.escape_string(content)
       sql = "insert into c_data(url, \
              content, forward, praise, comment,classify,medium,media,company,province,createtime,dateline,title,city) \
              values('%s', '%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', '%s')" % \
             (url, content, forward, praise, comment, classify, medium, media, company, province,createtime,dateline,title, city)

       '''sql = "insert into c_data(url,content, flag, forward, praise, comment) values('%s', '%s', '%s', '%s', '%s', '%s' )"'''
       cursor = self.db.cursor()

       # 执行sql语句
       cursor.execute(sql)

       insert_id =  self.db.insert_id()

       print insert_id
       cursor.close()
       # 提交到数据库执行
       self.db.commit()
       #except:
          # 发生错误时回滚
          #self.db.rollback()

        # 关闭数据库连接
       #self.db.close()
       return insert_id
    def close(self):
        self.db.close()

    def delete(self):
       sql = "delete from employee where age = '%d'" % (21)
       cursor = self.db.cursor()
       cursor.execute(sql)
       self.db.commit()
       self.db.close()

       print ''

    def update(self, forward, praise, comment, id,createtime):
        # content = MySQLdb.escape_string(content)
        sql = "update c_data set forward='%s', praise='%s', comment='%s',createtime='%s' where id = '%s'" % (
        forward, praise, comment, createtime, id)


        print sql



        cursor = self.db.cursor()

        # 执行sql语句
        cursor.execute(sql)

        cursor.close()
        # 提交到数据库执行
        self.db.commit()
        # except:
        # 发生错误时回滚
        # self.db.rollback()

        # 关闭数据库连接
        # self.db.close()

    def queryByFlag(self,flag):
       sql = "select * from c_data where flag = '%s'" % (flag)
       cursor = self.db.cursor()
       cursor.execute(sql)

       # 获取所有记录列表
       results = cursor.fetchall()

       self.db.close()
       if len(results):
           return True
       else:
           return False

    def start(self):
        try:
            #DbUtils.create(self)
            #DbUtils.insert(self)
            #DbUtils.delete(self)
            #DbUtils.update(self)
            #DbUtils.query(self)
            print DbUtils.queryByFlag(self,'1')
        except Exception, e:
            print "Error: ", e

#DbUtils().update("2", "2","2",1)